package thread.Threadlocal;

public class ThreadLocalTest2 {
	  public static void main(String[] args) { 
          MyThreadLocal2 tlt = new MyThreadLocal2(); 
          Thread t1 = new TestThread(tlt); 
          Thread t2 = new TestThread(tlt); 
          Thread t3 = new TestThread(tlt); 
          Thread t4 = new TestThread(tlt); 
          t1.start(); 
          t2.start(); 
          t3.start(); 
          t4.start(); 

  } 
}


class MyThreadLocal2 { 
    //定义了一个ThreadLocal变量，用来保存int或Integer数据 
    private ThreadLocal<Integer> tl = new ThreadLocal<Integer>() { 
            @Override 
            protected Integer initialValue() { 
                    return 0; 
            } 
    }; 

    public Integer getNextNum() { 
            //将tl的值获取后加1，并更新设置t1的值 
            tl.set(tl.get() + 1); 
            return tl.get(); 
    } 
}

class TestThread extends Thread { 
    private MyThreadLocal2 tlt = new MyThreadLocal2(); 

    public TestThread(MyThreadLocal2 tlt) { 
            this.tlt = tlt; 
    } 

    @Override 
    public void run() { 
            for (int i = 0; i < 3; i++) { 
                    System.out.println(Thread.currentThread().getName() + "\t" + tlt.getNextNum()); 
            } 
    } 
}

/*
 * Thread-1	1
Thread-1	2
Thread-1	3
Thread-3	1
Thread-3	2
Thread-3	3
Thread-0	1
Thread-0	2
Thread-0	3
Thread-2	1
Thread-2	2
Thread-2	3
 * */